package com.yangye.pisystem.controller;

import com.yangye.picommon.model.PiResult;
import com.yangye.picommon.model.page.PageRequest;
import com.yangye.picommon.model.page.PageResult;
import com.yangye.pisystem.domain.SysRole;
import com.yangye.pisystem.domain.SysRoleMenu;
import com.yangye.pisystem.dto.SysRoleMenuDTO;
import com.yangye.pisystem.service.SysRoleMenuService;
import com.yangye.pisystem.service.SysRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author yangye
 * @date 2019/7/31
 */
@RestController
@RequestMapping("/sys/roles/")
public class SysRoleController {

	@Autowired
	private SysRoleService sysRoleService;
	@Autowired
	private SysRoleMenuService sysRoleMenuService;

	/**
	 * 新增
	 * @param sysRole
	 * @return
	 */
	@PostMapping("/")
	@PreAuthorize("hasAuthority('sys:role:add')")
	PiResult add(@RequestBody SysRole sysRole) {
		sysRoleService.add(sysRole);
		return PiResult.succeed();
	}

	/**
	 * 删除
	 * @param id
	 * @return
	 */
	@DeleteMapping("/{id}")
	@PreAuthorize("hasAuthority('sys:role:remove')")
	PiResult remove(@PathVariable("id") Long id) {
		sysRoleService.remove(id);
		return PiResult.succeed();
	}

	/**
	 * 修改
	 * @param sysRole
	 * @return
	 */
	@PutMapping("/")
	@PreAuthorize("hasAuthority('sys:role:update')")
	PiResult update(@RequestBody SysRole sysRole) {
		sysRoleService.update(sysRole);
		return PiResult.succeed();
	}

	/**
	 * 详情
	 * @param id
	 * @return
	 */
	@GetMapping("/{id}")
	@PreAuthorize("hasAuthority('sys:role:view')")
	PiResult get(@PathVariable("id") Long id) {
		return PiResult.succeed(sysRoleService.get(id));
	}

	/**
	 * 分页列表
	 * @param sysRole
	 * @param pageModel
	 * @return
	 */
	@GetMapping("/page")
	@PreAuthorize("hasAuthority('sys:role')")
	PiResult findPage(SysRole sysRole, PageRequest pageRequest) {
		PageResult<SysRole> page = sysRoleService.findPage(sysRole, pageRequest);
		return PiResult.succeed(page);
	}

	/**
	 * 获取全部
	 * @param sysRole
	 * @return
	 */
	@GetMapping("/all")
	@PreAuthorize("hasAuthority('sys:role')")
	PiResult findAll(SysRole sysRole) {
		List<SysRole> list = sysRoleService.findAll(sysRole);
		return PiResult.succeed(list);
	}

	/**
	 * 角色添加菜单权限
	 * @return
	 */
	@PostMapping("/menus")
	@PreAuthorize("hasAuthority('sys:role:auth')")
	PiResult saveMenus(@RequestBody SysRoleMenuDTO sysRoleMenuDTO) {
		sysRoleMenuService.updateMenu(sysRoleMenuDTO);
		return PiResult.succeed();
	}

	/**
	 * 获取角色关联的菜单权限
	 * @param roleId
	 * @return
	 */
	@GetMapping("/menus/{roleId}")
	PiResult findMenus(@PathVariable("roleId") Long roleId) {
		List<SysRoleMenu> list = sysRoleMenuService.findByRoleId(roleId);
		return PiResult.succeed(list);
	}
}
